package cn.luckdou.system.service.impl.we_chat_location;

import cn.luckdou.system.mapper.we_chat_location.WeChatLocationMapper;
import cn.luckdou.system.model.we_chat_location.WeChatLocation;
import cn.luckdou.system.service.we_chat_location.IWeChatLocationService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import cn.luckdou.WeChat.utils.HttpUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 微信用户位置 服务实现类
 * </p>
 *
 * @author Dadou
 * @since 2017-12-07
 */
@Service
public class WeChatLocationServiceImpl extends ServiceImpl<WeChatLocationMapper, WeChatLocation> implements IWeChatLocationService {
    @Autowired
    private WeChatLocationMapper weChatLocationMapper;

    @Override
    @Transactional
    public boolean getLocation(long l) {
        WeChatLocation weChatLocation = weChatLocationMapper.selectById(l);
        if (weChatLocation==null) return false;
        String lable=null;
        try{
            String s = HttpUtils.sendGet(getUrl(weChatLocation));
            s= s.substring(s.indexOf("(")+1, s.length() - 1);
            JSONObject json = JSONObject.fromObject(s);
            JSONObject result = json.getJSONObject("result");
            String formatted_address = result.getString("formatted_address");
            String sematic_description = result.getString("sematic_description");
            lable=formatted_address+" - "+sematic_description;
            System.out.println(s);
        }catch (Exception e){
            return false;
        }
        List<WeChatLocation> list = weChatLocationMapper.selectList(new EntityWrapper<WeChatLocation>()
                .eq("latitude",weChatLocation.getLatitude())
                .eq("longitude",weChatLocation.getLongitude()));
        if (list==null || list.size()<=0) return false;
        Integer integer=0;
        for (WeChatLocation location : list) {
            location.setLable(lable);
            location.setUpdatedTime(new Date());
            integer += weChatLocationMapper.updateAllColumnById(location);
        }
        return integer>0?true:false;
    }

    private String getUrl(WeChatLocation weChatLocation){
        return "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location="
                +weChatLocation.getLatitude()+","
                +weChatLocation.getLongitude()
                +"&output=json&pois=1&ak=IbolQkOKOKGeAeWXNkmuy5ghAYwGO6ca&coordtype=wgs84ll";
    }
}
